package com.achao.achaomq.thread;

import com.achao.achaomq.constants.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;


/**
 * 全局线程池
 */
@Slf4j
@Component
public class GlobalThreadPool {

    //CPU密集型适用-核心线程数
    private final static Integer THREAD_SIZE = Runtime.getRuntime().availableProcessors();

    //初始化线程池
    private static ExecutorService sendAsync = new ThreadPoolExecutor(
            THREAD_SIZE,
            THREAD_SIZE * 2,
            CommonConstants.TASK_OUT_TIME,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(CommonConstants.QUEUE_SIZE),
            r -> {
                Thread thread = new Thread(r);
                thread.setName("achao_global_thread_pool");
                return thread;
            },
            (r, executor) -> log.error("async save error,runnable:{},executor:{}",r,executor)
    );

    //获取全局线程池
    public ExecutorService getExecutorService(){
        return sendAsync;
    }

}
